//
//  DDTabRewardVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/6/28.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDTabHelpVC.h"
#import "DDNetWorkAPIClient.h"
#import "DDTabRewardVCCell.h"
#import "DDTopic.h"
#import "UIImageView+WebCache.h"
#import "GlobalDefine.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "FootToolButtonView.h"
#import "XHTwitterPaggingViewer.h"
#import "TNColorScrollViewController.h"
#import "DDQuestionView.h"
#import "DDTagVC.h"
#import "DDTagDB.h"
#import "DDShareViewController.h"

#import "DDCkdaQuestion.h"

#import "DOPDropDownMenu.h"
#import "ModelQuestionCourse.h"
#import "WXViewController.h"

#define kHRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
@interface DDTabHelpVC ()<DOPDropDownMenuDataSource, DOPDropDownMenuDelegate>
{
    XHTwitterPaggingViewer *twitterPaggingViewer;
}
@property (nonatomic,strong)NSMutableArray *datas;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,assign)int pageIndex;
@property (nonatomic,assign)int pageSize;

@property (nonatomic,strong) DDTopicDataCellModel *model;
@property (nonatomic,strong) NSArray *questions;
@property (nonatomic, strong) TNColorScrollViewController *colorScrollVC;

@property (nonatomic, copy) NSArray *searchs;
@property (nonatomic, strong)NSMutableArray *allArray;

@property (nonatomic, assign)NSInteger reImage;

@property (nonatomic,strong) NSString *searchText;
@end

@implementation DDTabHelpVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationController setNavigationBarHidden:YES];
    //self.navigationController.navigationBarHidden = YES;
    //    self.navigationController.navigationBar.hidden = NO;
    [self addNavigatorTitle:NSLocalizedString(@"晒晒", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    
    //    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    //    backBtn.frame = CGRectMake(0, 20, self.view.frame.size.width, 44);
//    [self AddLeftBtnAction:nil normal:@"top_返回" selected:@"top_返回" action:^{
//        [self dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popViewControllerAnimated:YES];
//    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:@"reload" object:nil];
    
    [self createUI];
    [self createData];
 
    //[self addSearchBar];
}

-(void)reload
{
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createUI
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(reloadPostData)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"别再拉了,裤子要被拉下来了...";
    
    self.tableView.footerPullToRefreshText = @"上提可以刷新了";
    self.tableView.footerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.footerRefreshingText = @"别再拉了,裤子要被拉下来了...";
}

- (void)createData
{
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(popTagView:) name:@"popTagView" object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(clearPopTagView) name:@"clearTagView" object:nil];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.01f)];
    
    _datas = [NSMutableArray array];
    _pageSize = 10;
    _pageIndex = 0;
    
    _reImage = 0;
}

-(void)clearPopTagView
{
    [[self.colorScrollVC.view viewWithTag:10001] removeFromSuperview];
}

- (void)popTagView:(NSNotification *)note
{
    UIView *view = [self.colorScrollVC.view viewWithTag:10001];
    if (view) {
        [self clearPopTagView];
        return;
    }
    
    DDTagVC * _tagVC = [[DDTagVC alloc] initWithNibName:@"DDTagVC" bundle:nil];
    [self.colorScrollVC addChildViewController:_tagVC];
    NSDictionary *dict = note.object;
    _tagVC.x = [dict objectForKey:@"x"];
    _tagVC.y = [dict objectForKey:@"y"];
    _tagVC.index = [dict objectForKey:@"index"];
    _tagVC.qid = [dict objectForKey:@"qid"];
    _tagVC.page = [dict objectForKey:@"page"];
    CGRect rect = _tagVC.view.frame;
    _tagVC.view.frame = CGRectMake((self.colorScrollVC.view.frame.size.width-rect.size.width)/2, self.view.frame.size.height, rect.size.width, rect.size.height);
    _tagVC.view.tag = 10001;
    [self.colorScrollVC.view addSubview:_tagVC.view];
    _tagVC.view.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _tagVC.view.frame = CGRectMake((self.colorScrollVC.view.frame.size.width-rect.size.width)/2, self.colorScrollVC.view.frame.size.height/2, rect.size.width, rect.size.height);
    }];
    
    int selectPage = _tagVC.page.integerValue - 1;
    __weak DDTabHelpVC *weakSelf = self;
    _tagVC.result = ^(NSString *result,id object,NSString *type)
    {
        NSArray *views = weakSelf.colorScrollVC.view.scrollView.subviews;
        if (views.count > 0) {
            DDQuestionView *qview = views[selectPage];
            [qview.tableView reloadData];
        }
        //[[NSNotificationCenter defaultCenter]postNotificationName:@"addMedia" object:weakSelf];
    };
}


#pragma mark - 私有方法
-(void)reloadPostData
{
    _pageIndex = 0;
    NSDictionary *params = @{@"type":@"0",@"pageIndex":[NSString stringWithFormat:@"%d",_pageIndex],@"pageSize":[NSString stringWithFormat:@"%d",_pageSize]};
    DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
    [netwrok mainTopicList:params completionBlock:^(BOOL isSuccess, NSString *message, NSString *status,id object) {
        DDTopic *topic = (DDTopic *)object;
        _datas = [NSMutableArray arrayWithArray:topic.list];
        _allArray = _datas;
        
        if (_searchText && ![_searchText isEqualToString:@"全部"]) {
            NSMutableArray *tempDatas = [NSMutableArray array];
            for (DDTopicDataCellModel *model in _allArray) {
                if ([_searchText isEqualToString:model.courseName]) {
                    [tempDatas addObject:model];
                }
            }
            _datas = tempDatas;
        }
        
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
    }];
    
}
-(void)footerRereshing
{
    _pageIndex++;
    NSDictionary *params = @{@"type":@"0",@"pageIndex":[NSString stringWithFormat:@"%d",_pageIndex],@"pageSize":[NSString stringWithFormat:@"%d",_pageSize]};
    DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
    [netwrok mainTopicList:params completionBlock:^(BOOL isSuccess, NSString *message, NSString *status,id object) {
        DDTopic *topic = (DDTopic *)object;
        [_datas addObjectsFromArray:topic.list];
        _allArray = _datas;
        
        if (_searchText && ![_searchText isEqualToString:@"全部"]) {
            NSMutableArray *tempDatas = [NSMutableArray array];
            for (DDTopicDataCellModel *model in _allArray) {
                if ([_searchText isEqualToString:model.courseName]) {
                    [tempDatas addObject:model];
                }
            }
            _datas = tempDatas;
        }
        
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
    }];
}

- (NSString *)convertTime:(NSString *)time
{
    if (!time || [@"" isEqualToString:time]) {
        return @"";
    }
    
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    long a =  [timeSp longLongValue] - time.longLongValue/1000;
    
    long day = a/(3600*24);
    
    if (day < 360 && day > 30) {
        return [NSString stringWithFormat:@"%ld个月前",day/30];
    }
    else if (day >360){
        return [NSString stringWithFormat:@"%ld年以前",day/360];
    }
    else if (day == 0)
    {
        long second = a/3600;
        if (second > 0 && second < 24) {
            return [NSString stringWithFormat:@"%ld小时前",second];
        }else{
            return [NSString stringWithFormat:@"%ld分钟前",a/60];
        }
        
    }
    else if (day > 1 && day < 6){
        return [NSString stringWithFormat:@"%ld天前",day];
    }else{
        //实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式,这里可以设置成自己需要的格式
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        //用[NSDate date]可以获取系统当前时间
        NSDate *d = [NSDate dateWithTimeIntervalSince1970:time.longLongValue/1000];
        NSString *dateStr = [dateFormatter stringFromDate:d];
        return dateStr;
    }
    return @"";
}



#pragma mark -UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datas.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 100;
    DDTopicDataCellModel *topicModel = [_datas objectAtIndex:indexPath.section];
    NSArray *questions = topicModel.questions;
    NSArray *bodys = questions.count > 0 ?((DDTopicQuestion *)questions[0]).body : nil;
    bool isimage = NO;
    bool istext = NO;
    for(int i = 0; i < bodys.count;i++)
    {
        DDTopicQuestionBody *body = bodys[i];
        NSString *type = body.type;
        if ([type isEqualToString:@"IMAGE"])
        {
           // if (_reImage == 0) {
            if (isimage) {
                continue;
            }
                 height = height + 130;
            isimage = YES;
                _reImage ++;
           // }
           
        }
        else if([type isEqualToString:@"TEXT"])
        {
            CGSize size = [self autoLabelString1:tableView string:body.text];
            if (istext) {
                continue;
            }
            height = height + size.height + 30;
            istext = YES;
        }
    }
    
    
    return height;
}
- (CGSize)autoLabelString1:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(view.frame.size.width - 10,60);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

- (CGSize)autoLabelString:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(view.frame.size.width - 10,2000);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

{
    return 5;
}

//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    static NSString *footIdentifier = @"FootToolButtonView";
//    __weak DDTabHelpVC *weakSelf = self;
//    FootToolButtonView *footView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:footIdentifier];
//    if(!footView) {
//        //    [tableView registerClass:[CustomHeaderView class] forHeaderFooterViewReuseIdentifier:HeaderIdentifier];
//        footView = [[[NSBundle mainBundle] loadNibNamed:@"FootToolButtonView"
//                                                  owner:self
//                                                options:nil] objectAtIndex:0];
//    }
//    footView.section = section;
//    DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
//    if ([topicModel.markResult isEqual:@"-1"]) {
//        footView.favBtn.selected = NO;
//    }else{
//        footView.favBtn.selected = YES;
//    }
//    
//    if([topicModel.answered boolValue]){
//        [footView.replyBtn setTitle:@"已回答" forState:UIControlStateNormal];
//    }
//
//    
//    footView.SubmitFavButtonBlock = ^(UIButton *button,NSInteger section){
//        button.selected = !button.selected;
//        if (button.selected) {
//            DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
//            DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
//            [network mainMarkSave:@{@"topicId":topicModel.id,@"type":@"0"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//                NSLog(@"%@",object);
//            }];
//        }else{
//            DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
//            //NSMutableArray *array = [NSMutableArray array];
//            //[array addObject:topicModel.id];
//            DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
//            [network mainMarkRemove:@{@"topicIds":topicModel.id} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//                NSLog(@"%@",object);
//            }];
//        }
//    };
//    footView.SubmitShareButtonBlock = ^(UIButton *button,NSInteger section){
//        DDShareViewController *share = [[DDShareViewController alloc] initWithNibName:@"DDShareViewController" bundle:nil];
//        share.view.frame = CGRectMake(0,CGRectGetHeight([[UIScreen mainScreen] bounds])-270 , CGRectGetWidth([[UIScreen mainScreen] bounds]), 150);
//        [weakSelf addChildViewController:share];
//        [weakSelf.view addSubview:share.view];
//        //[DDShareViewController  showShareWithController:self];
//
//    };
//    footView.SubmitReplayButtonBlock = ^(UIButton *button,NSInteger section){
//        [self gotoDetailPage:section];
//    };
//    
//    //    UIView * footView =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 600, 50)];
//    //    [footView setBackgroundColor:[UIColor whiteColor]];
//    //
//    //    UILabel *hLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 600, 1)];
//    //    hLine.backgroundColor = [UIColor lightGrayColor];
//    //    [footView addSubview:hLine];
//    //
//    //
//    //    UIButton *favButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    //    favButton.frame = CGRectMake( 30, 10, 56, 36);
//    //    [favButton setImage:[UIImage imageNamed:@"icon_header"] forState:UIControlStateNormal];
//    //    [favButton setTitle:@"收藏" forState:UIControlStateNormal];
//    //    [favButton addTarget:self action:@selector(favAction:) forControlEvents:UIControlEventTouchUpInside];
//    //    favButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:14.0];
//    //    [favButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
//    //    [favButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    //    [favButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    //    [footView addSubview:favButton];
//    //
//    //    UILabel *vLine = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:favButton sp:20], 10, 1, 30)];
//    //    vLine.backgroundColor = [UIColor lightGrayColor];
//    //    [footView addSubview:vLine];
//    //
//    //
//    //    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    //    shareButton.frame = CGRectMake([self xPostiong:favButton sp:40],favButton.frame.origin.y, 56, 36);
//    //    [shareButton setImage:[UIImage imageNamed:@"icon_share"] forState:UIControlStateNormal];
//    //    [shareButton setTitle:@"分享" forState:UIControlStateNormal];
//    //    shareButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:14.0];
//    //    [shareButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
//    //    [shareButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    //    [shareButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
//    //    [shareButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    //    [footView addSubview:shareButton];
//    //
//    //    UILabel *vLine2 = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:shareButton sp:40], 10, 1, 30)];
//    //    vLine2.backgroundColor = [UIColor lightGrayColor];
//    //    [footView addSubview:vLine2];
//    //
//    //
//    //    UIButton *answerButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    //    answerButton.frame = CGRectMake([self xPostiong:shareButton sp:40], favButton.frame.origin.y, 100, 36);
//    //    [answerButton setImage:[UIImage imageNamed:@"icon_pen"] forState:UIControlStateNormal];
//    //    [answerButton setTitle:@"马上回答" forState:UIControlStateNormal];
//    //    answerButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:14.0];
//    //    [answerButton addTarget:self action:@selector(answerAction:) forControlEvents:UIControlEventTouchUpInside];
//    //    [answerButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
//    //    [answerButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    //    [answerButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    //    [footView addSubview:answerButton];
//    
//    return footView;
//}

//- (void)gotoDetailPage:(NSInteger)section
//{
//    
//    DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
//    _model = topicModel;
//    NSArray *questions = topicModel.questions;
//    _questions = questions;
//    
//    
//    
//    NSMutableArray *qustionViews = [NSMutableArray array];
//    for (int i = 0; i < _questions.count; i++)
//    {
//        DDTopicQuestion *question = _questions[i];
//        TNColorViewData *viewData = [[TNColorViewData alloc] initWithCustomClass:[DDQuestionView class]];
//        viewData.question = question;
//        viewData.page = i+1;
//        viewData.topicType = @"3";
//        viewData.total = questions.count;
//        [qustionViews addObject:viewData];
//    }
//    TNColorScrollViewConfig *config = [[TNColorScrollViewConfig alloc] initWithColorDataObjects:qustionViews bounces:YES showsHorizontalScrollIndicator:NO showsVerticalScrollIndicator:NO pagingEnabled:YES scrollHorizontal:YES];
//    
//    self.colorScrollVC = [[TNColorScrollViewController alloc] initWithColorScrollViewConfig:config displayMedia:YES cssStyle:DDCSSStyleAnswer];
//    self.colorScrollVC.topicID = _model.id;
//    self.colorScrollVC.topicType = @"3";
//    self.colorScrollVC.currentScrollerPage = ^(NSInteger currentPage){
//        //NSLog(@"%d",currentPage);
//    };
//     __weak DDTabHelpVC *weakSelf = self;
//    self.colorScrollVC.preScrollerPage = ^(NSInteger prePage){
//       
//        DDNetWorkAPIClient *netwrok = [[DDNetWorkAPIClient alloc]init];
//        DDTopicQuestion *question = weakSelf.questions[prePage];
//        DDQuestionView *questionView =  weakSelf.colorScrollVC.view.scrollView.subviews[prePage];
//        NSString *result = questionView.result;
//        
//        //答案集合上传
//        NSString *explanationJson = @"";
//        NSArray *answers = questionView.answers;
//        NSMutableArray *explanations = [NSMutableArray array];
//        NSString *answerString = @"";
//        if ([questionView.questionType isEqualToString:@"填空题"] || [questionView.questionType isEqualToString:@"简答题"]) {
//            NSDictionary *pngDict = @{@"type":@"TEXT",@"text":questionView.result?questionView.result:@"",@"url":@""};
//            [explanations addObject:pngDict];
//        }else{
//            answerString = questionView.result?questionView.result:@"";
//        }
//        
//        
//        for (int i = 0; i < answers.count ; i++) {
//            NSString *ext = [answers[i] pathExtension];
//            if ([ext isEqualToString:@"jpg"]) {
//                //                    NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":answers[i]};
//                //                    [explanations addObject:pngDict];
//                //保存泡泡标签
//                NSArray *tags =   [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' ",questionView.question.id] orderBy:nil offset:0 count:0];
//                NSMutableArray *filterArray = [NSMutableArray array];
//                for (int i = 0; i < tags.count; i++) {
//                    DDTagDB *tag = tags[i];
//                    if (![filterArray containsObject:tag.tagIndex]) {
//                        [filterArray addObject:tag.tagIndex];
//                    }
//                    
//                }
//                NSArray *sortArray = [NSArray arrayWithArray:filterArray];
//                [sortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//                    
//                    NSString *o1 = (NSString *)obj1;
//                    NSString *o2 = (NSString *)obj2;
//                    if ([o1 integerValue] > [o2 integerValue]) {
//                        return NSOrderedAscending;
//                    }
//                    if ([o1 integerValue] < [o2 integerValue]) {
//                        return NSOrderedDescending;
//                    }
//                    return NSOrderedSame;
//                }];
//                
//                if (sortArray.count > i) {
//                    NSArray *tagss =   [DDTagDB searchWithWhere:[NSString stringWithFormat:@"qid='%@' AND tagIndex='%@'",questionView.question.id,sortArray[i]] orderBy:nil offset:0 count:0];
//                    
//                    NSMutableArray *tagLabels = [NSMutableArray array];
//                    
//                    for (DDTagDB *tagdb in tagss) {
//                        if ([tagdb.type isEqualToString:@"IMAGE"]||[tagdb.type isEqualToString:@"AUDIO"]) {
//                            NSDictionary *dict = @{@"type":[tagdb.type isEqualToString:@"AUDIO"]?@"VOICE":tagdb.type,@"x":[NSNumber numberWithInteger:[tagdb.x integerValue]],@"y":[NSNumber numberWithInteger:[tagdb.y integerValue]],@"url":tagdb.result};
//                            [tagLabels addObject:dict];
//                        }else if ([tagdb.type isEqualToString:@"TEXT"]){
//                            NSDictionary *dict = @{@"type":tagdb.type,@"x":[NSNumber numberWithInteger:[tagdb.x integerValue]],@"y":[NSNumber numberWithInteger:[tagdb.y integerValue]],@"text":tagdb.result};
//                            [tagLabels addObject:dict];
//                        }
//                    }
//                    NSDictionary *pngDict = @{@"type":@"IMAGE",@"url":answers[i],@"labels":tagLabels};
//                    [explanations addObject:pngDict];
//                    
//                }
//                
//                
//            }
//            if ([ext isEqualToString:@"caf"]) {
//                NSDictionary *cafDict = @{@"type":@"VOICE",@"url":answers[i]};
//                [explanations addObject:cafDict];
//            }
//            
//        }
//        
//        NSError *error;
//        NSData * JSONData = [NSJSONSerialization dataWithJSONObject:explanations
//                                                            options:kNilOptions
//                                                              error:&error];
//        explanationJson = [[NSString alloc]initWithData:JSONData encoding:NSUTF8StringEncoding];
//        
//        
//        [netwrok mainAnswerSave:@{@"topicId":weakSelf.model.id,@"qid":question.id,@"answer":answerString,@"costSeconds":@"10",@"explanations":explanationJson} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//            NSLog(@"%@",object);
//            if (object) {
//                
//            }
//            [MBProgressHUD showMessag:message toView:weakSelf.view];
//            
//        }];
//    };
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:self.colorScrollVC];
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    DDTopicDataCellModel *topicModel = [_datas objectAtIndex:indexPath.section];
    NSArray *questions = topicModel.questions;
    float start_X = 5;
    float start_Y = 5;
    
    UIImageView *header_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(start_X, start_Y, 50, 50)];
    //header_imageView.image = [UIImage imageNamed:@"user_header"];
    [header_imageView sd_setImageWithURL:[NSURL URLWithString:topicModel.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"首页列表头像-通用"] options:SDWebImageRefreshCached];
    header_imageView.layer.cornerRadius = 25.0;
    header_imageView.layer.masksToBounds = YES;

    [cell.contentView addSubview:header_imageView];
    
    UILabel *name_label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:header_imageView sp:10],header_imageView.frame.origin.y+5 , 200, 24)];
    name_label.text = topicModel.userName;
    name_label.textColor = RGB(124,203,203);
    [cell.contentView addSubview:name_label];
    
    UILabel *school_label = [[UILabel alloc] initWithFrame:CGRectMake(name_label.frame.origin.x,[self yPostiong:name_label sp:5] , 200, 16)];
    school_label.text = topicModel.school;//@"1天前";
    school_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
    school_label.textColor = [UIColor lightGrayColor];
    [cell.contentView addSubview:school_label];
    
    UILabel *time_label = [[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width-70,[self yPostiong:name_label sp:5] , 200, 16)];
    time_label.text = [self convertTime:topicModel.createTime];//@"1天前";
    time_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
    time_label.textColor = [UIColor lightGrayColor];
    [cell.contentView addSubview:time_label];
    
    UIImageView *gold_imageview = [[UIImageView alloc] initWithFrame:CGRectMake(tableView.frame.size.width - 80, name_label.frame.origin.y+3, 15, 15)];
    gold_imageview.image = [UIImage imageNamed:@"icon_gold"];
//    [cell.contentView addSubview:gold_imageview];
//
//    UILabel *gold_label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:gold_imageview sp:4],  name_label.frame.origin.y+3, 70, 16)];
//    gold_label.text = topicModel.reward;
//    gold_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
//    gold_label.textColor = [UIColor orangeColor];
//    [cell.contentView addSubview:gold_label];
    
    NSArray *bodys = questions.count > 0 ?((DDTopicQuestion *)questions[0]).body : nil;
    int autoHeigth = 0;
    bool isimage = NO;
    bool istext = NO;
    for(int i = 0; i < bodys.count;i++)
    {
        DDTopicQuestionBody *body = bodys[i];
        NSString *type = body.type;
        if ([type isEqualToString:@"TEXT"]) {
            
            UILabel *content_label = [[UILabel alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:10] , tableView.frame.size.width -10, 18)];
            content_label.numberOfLines = 3;
            content_label.font = [UIFont fontWithName:@"Arial" size:17];
            content_label.text = body.text;
            CGSize size = [self autoLabelString1:tableView string:body.text];
            content_label.frame = CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:10+autoHeigth] , tableView.frame.size.width -10, size.height+40);
            if (istext) {
                continue;
            }
            autoHeigth += size.height + 40;
            istext = YES;
            [cell.contentView addSubview:content_label];
        }
        else if ([type isEqualToString:@"IMAGE"])
        {
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(header_imageView.frame.origin.x,[self yPostiong:header_imageView sp:5+autoHeigth], tableView.frame.size.width -10, 130.0)];
            if (isimage) {
                continue;
            }
            autoHeigth += 130 + 5;
            isimage = YES;
            [imageView setImageWithURL:[NSURL URLWithString:body.url] placeholderImage:[UIImage imageNamed:@"home_pic_04.png"]options:SDWebImageRefreshCached];
            //imageView.image = [self OriginImage:imageView.image scaleToSize:imageView.frame.size];
            //                imageView.clipsToBounds  = YES;
            //                imageView.contentMode = UIViewContentModeCenter|UIViewContentModeLeft;
            imageView.contentMode =  UIViewContentModeScaleAspectFill;
            //imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
            imageView.clipsToBounds  = YES;
            [cell.contentView addSubview:imageView];
            //content_label.frame = CGRectMake(header_imageView.frame.origin.x, [self yPostiong:imageView sp:0],tableView.frame.size.width -10, 44);
        }
    }
    
    //1.创建按钮对象
    UIButton *fans = [UIButton buttonWithType:UIButtonTypeSystem];
    //2.设置大小位置
    //fans.frame = CGRectMake(50, 250, 80, 40);
    fans.frame = CGRectMake(cell.contentView.frame.size.width-100,header_imageView.frame.size.height+autoHeigth+8, 40, 16);
    //3.设置按钮上的文字
    NSString *praise_num = [@" " stringByAppendingString:topicModel.praiseNum];
    [fans setTitle:praise_num forState:UIControlStateNormal];
    [fans setTitle:praise_num forState:UIControlStateHighlighted];
    [fans setImage:[UIImage imageNamed:@"zan_p"] forState:UIControlStateNormal];
    [fans setImage:[UIImage imageNamed:@"zan"] forState:UIControlStateHighlighted];
    //fans.backgroundColor = [UIColor lightGrayColor];
    //4. 添加事件
    [fans addTarget:self action:@selector(click_like_and_cancel) forControlEvents:UIControlEventTouchUpInside];
    //5. 添加按钮到视图中
    [cell.contentView addSubview:fans];
    

    
    //2.设置大小位置
    //fans.frame = CGRectMake(50, 250, 80, 40);
    
    UIImageView *comment_img_view = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width-50,header_imageView.frame.size.height+autoHeigth+8, 18, 16)];
    UILabel *comment_num_label = [[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width-28,header_imageView.frame.size.height+autoHeigth+8, 18, 16)];
    comment_num_label.text = topicModel.commentNum;//@"1天前";
    if (topicModel.commentNum==0) {
        comment_img_view.image = [UIImage imageNamed:@"pinlun"];
        comment_num_label.textColor = [UIColor lightGrayColor];
    }else{
        comment_img_view.image = [UIImage imageNamed:@"pinlun_p"];
        comment_num_label.textColor = kHRGB(0x33ccff);//RGB(51,204,255);
    }
    [cell.contentView addSubview:comment_img_view];
    comment_num_label.font = [UIFont fontWithName:@"Arial" size:16.0f];
    
    [cell.contentView addSubview:comment_num_label];

    
    return cell;
    
}

//- (void)click_like_and_cancel{
//    DDTopicDataCellModel *topicModel = [_datas objectAtIndex:section];
//    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
//        [network mainMarkSave:@{@"topicId":topicModel.id,@"type":@"0"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//    NSLog(@"%@",object);
//}];
//}
- (void)gotoCommentDetails:(NSString *)button {
    
    WXViewController *friendCircle = [WXViewController new];
    
    NSLog(@"ffriendCircle.topic_id=%@",friendCircle.topic_id);
    [self presentViewController:friendCircle animated:YES completion:nil];
//    WXViewController *wxVc = [WXViewController new];
//    [self presentViewController:wxVc animated:YES completion:NULL];
    //friendCircle.delegate = self;
    //[self.navigationController pushViewController:collectionVC animated:YES];
    //friendCircle.hidesBottomBarWhenPushed = YES;
    //[self.navigationController pushViewController:friendCircle animated:YES];
    
    
    //WXViewController *ickImageViewController = [[WXViewController alloc] init];
    
    //[self.navigationController pushViewController: ickImageViewController animated:true];
}

- (CGSize)autoSize:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(1000,44);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

-(UIImage *)OriginImage:(UIImage *)image scaleToSize:(CGSize)size{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
//- (NSIndexPath *)tableView:tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return nil;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    //[self gotoDetailPage:indexPath.section];
    DDTopicDataCellModel *topicModel = [_datas objectAtIndex:indexPath.section];
//    WXViewController *topicID = [[WXViewController alloc] init];
//    topicID.topic_id = topicModel.id;
//    topicID.Publish_uid = topicModel.uid;
//    NSLog(@"topicID.topic_id=%@",topicID.topic_id);
//    NSLog(@"topicID.Publish_uid=%@",topicID.Publish_uid);
    [self ckdaQuestion:topicModel showAnswer:NO];
}

-(float) xPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.width+view.frame.origin.x + sp;
}

-(float) yPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.height+view.frame.origin.y + sp;
}


- (void)favAction:(UIButton *)sender
{
    NSLog(@"fav");
}
- (void)answerAction:(UIButton *)sender
{
    NSLog(@"answer");
}
- (void)shareAction:(UIButton *)sender
{
    NSLog(@"share");
}

-(void)ckdaQuestion:(DDTopicDataCellModel *)topicModel showAnswer:(BOOL)isShow
{
    _questions = topicModel.questions;
    
    NSLog(@"topicModel.userName=%@",topicModel.userName);
    NSLog(@"topicModel.title=%@",topicModel.title);
    NSLog(@"topicModel.typeName=%@",topicModel.typeName);
    
    NSMutableArray *qustionViews = [NSMutableArray array];
    for (int i = 0; i < _questions.count; i++)
    {
        DDTopicQuestion *question = _questions[i];
        TNColorViewData *viewData = [[TNColorViewData alloc] initWithCustomClass:[DDCkdaQuestion class]];
        viewData.question = question;
        viewData.page = i+1;
        viewData.total = _questions.count;
        viewData.topic = topicModel;
        //viewData.typeIndex = _typeIndex;
        viewData.showAnswer = isShow;
        [qustionViews addObject:viewData];
        
    }
    TNColorScrollViewConfig *config = [[TNColorScrollViewConfig alloc] initWithColorDataObjects:qustionViews bounces:YES showsHorizontalScrollIndicator:NO showsVerticalScrollIndicator:NO pagingEnabled:YES scrollHorizontal:YES];
    
    self.colorScrollVC = [[TNColorScrollViewController alloc] initWithColorScrollViewConfig:config displayMedia:NO cssStyle:DDCSSStyleReplay];
    self.colorScrollVC.topicID = _model.id;
    self.colorScrollVC.currentScrollerPage = ^(NSInteger currentPage){
        NSLog(@"%ld",(long)currentPage);
    };
    
    WXViewController *wxvc=[WXViewController new];
    wxvc.topic_id = topicModel.id;
    wxvc.Publish_uid = topicModel.uid;
    wxvc.helpTopicCellModel = topicModel;
    NSLog(@"wxvc.topic_id=%@",wxvc.topic_id);
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:self.colorScrollVC];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ToDetailPage" object:wxvc];
}


////搜索栏
//-(void)addSearchBar
//{
//    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
//    NSMutableArray *array = [NSMutableArray array];
//    [array addObject:@"全部"];
//    self.searchs = array;
//    __weak DDTabHelpVC *weakSelf = self;
//    [network mainCoursetList:@{@"type":@"0"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//        ModelQuestionCourse *courses = (ModelQuestionCourse*)object;
//        for (ModelQuestionCourseElement *element in courses.info_data) {
//            [array addObject:element.info_title];
//        }
//        
//        weakSelf.searchs = array;
//        // NSLog(@"%@",object);
//    }];
//    
//    //_searchs = @[@"全部",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选",@"单选",@"多选"];
//    //UIView *view  = [[UIView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width,40)];
//    
//    DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 20) andHeight:50];
//    menu.dataSource = self;
//    menu.delegate = self;
//    
//    [self.view addSubview:menu];
//    
//    //_tableView.tableHeaderView = menu;
//}

- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu {
    return 1;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column {
    return self.searchs.count;
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath {
    switch (indexPath.column) {
        case 0: return self.searchs[indexPath.row];
            break;
        default:
            return nil;
            break;
    }
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath {
    NSLog(@"column:%li row:%li", (long)indexPath.column, (long)indexPath.row);
    NSLog(@"%@",[menu titleForRowAtIndexPath:indexPath]);
    NSString *title = [menu titleForRowAtIndexPath:indexPath];
    
    
    _searchText = title;
    
    static NSString *prediStr1 = @"SELF LIKE '*'",
    *prediStr2 = @"SELF LIKE '*'",
    *prediStr3 = @"SELF LIKE '*'";
    switch (indexPath.column) {
        case 0:{
            if (indexPath.row == 0) {
                prediStr1 = @"SELF LIKE '*'";
            } else {
                prediStr1 = [NSString stringWithFormat:@"SELF CONTAINS '%@'", title];
            }
        }
            break;
            //        case 1:{
            //            if (indexPath.row == 0) {
            //                prediStr2 = @"SELF LIKE '*'";
            //            } else {
            //                prediStr2 = [NSString stringWithFormat:@"SELF CONTAINS '%@'", title];
            //            }
            //        }
            //            break;
            //        case 2:{
            //            if (indexPath.row == 0) {
            //                prediStr3 = @"SELF LIKE '*'";
            //            } else {
            //                prediStr3 = [NSString stringWithFormat:@"SELF CONTAINS '%@'", title];
            //            }
            //        }
            
        default:
            break;
    }
    //NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ AND %@ AND %@",prediStr1,prediStr2,prediStr3]];
    //NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@",prediStr1]];
    
    
    //NSPredicate* predicate=[NSPredicate predicateWithFormat:@"_datas.courseName == %@",title];
    NSMutableArray *tempDatas = [NSMutableArray array];
    for (DDTopicDataCellModel *model in _allArray) {
        if ([title isEqualToString:model.courseName]) {
            [tempDatas addObject:model];
        }
    }
    if (![title isEqualToString:@"全部"]) {
        _datas = tempDatas;
    }else{
        _datas = _allArray;
    }
    //_datas=[arr filteredArrayUsingPredicate:predicate];
    //NSLog(@"%@",results);
    
    //self.results = [self.originalArray filteredArrayUsingPredicate:predicate];
    [self.tableView reloadData];
}

- (BOOL) searchText:(UITextField *)textField
{
    
    NSMutableArray *tempDatas = [NSMutableArray array];
    if ([textField.text isEqualToString:@""]) {
        _datas = _allArray;
        [self.tableView reloadData];
        return YES;
    }
    
    NSLog(@"text:%@",textField.text);
    for (DDTopicDataCellModel *model in _datas) {
        NSArray *array = model.questions;
        if (array.count > 0) {
            DDTopicQuestion *question = array[0];
            //NSArray *array1 = question.body;
            //if (array1.count > 0) {
            DDTopicQuestionBody *body = question.body[0];
            if (body.text&&[body.text rangeOfString:textField.text].location != NSNotFound) {
                [tempDatas addObject:model];
                //   }
            }
        }
    }
    _datas = tempDatas;
    [self.tableView reloadData];
    return YES;
}
@end
